package com.qu.waibao.search;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.example.xlhratingbar_lib.XLHRatingBar;
import com.google.gson.reflect.TypeToken;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.Order;
import com.qu.waibao.bean.PayResult;
import com.qu.waibao.home.activity.PublishDetailActivity;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.my.adapter.PublishAdapter;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.LogUtil;
import com.qu.waibao.utils.PayUitl;
import com.qu.waibao.utils.ToastUtil;
import com.qu.waibao.widget.RecyclerRefreshLayout;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import info.wangchen.simplehud.SimpleHUD;

public class OrderSearchActivity extends BaseActivity implements RecyclerRefreshLayout.SuperRefreshLayoutListener,BaseRecyclerAdapter.OnItemClickListener,
        PublishAdapter.OnItemButtonClickListener,View.OnClickListener{
    @BindView(R.id.mRecyclerRefreshLayout)
    RecyclerRefreshLayout mRecyclerRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.mRoot)
    LinearLayout mRoot;
    private PublishAdapter adapter;
    private boolean isRefreshing = true;
    private int pageNum = 1;
    private String ordertype = "";
    private String keywords = "";
    private String paytype = "";
    private IWXAPI api;//微信支付参数
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.qu.waibao.PAYMENTSUCCESS")){
                onRefreshing();
            }
        }
    };
    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            ordertype = bundle.getString("ordertype","");
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_order_search;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mRecyclerRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mRecyclerRefreshLayout.setSuperRefreshLayoutListener(this);
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_UP){
                    keywords = et_search.getText().toString().trim();
                    if(TextUtils.isEmpty(keywords)){
                        keywords = "";
                    }
                    isRefreshing = true;
                    requestData();
                    return true;
                }
                return false;
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qu.waibao.PAYMENTSUCCESS");
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void initData() {
        super.initData(); adapter = new PublishAdapter(this, BaseRecyclerAdapter.ONLY_FOOTER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        if(adapter.getItems().size() == 0){
            mRecyclerRefreshLayout.setRefreshing(true);
            onRefreshing();
        }
        adapter.setOnItemClickListener(this);
    }

    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.order_list_get);
        map.put("userid", AppConfig.getString("userid"));
        map.put("ordertype",ordertype);
        map.put("state","");
        map.put("keyword",keywords);
        map.put("pagenum",pageNum+"");
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                List<Order> list = GsonUtil.createGson().fromJson(result,
                        new TypeToken<List<Order>>(){}.getType());
                if(isRefreshing){
                    adapter.clear();
                    adapter.addAll(list);
                    if(list.size() < 12){
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                    }
                }else {
                    adapter.addAll(list);
                    if(list.size() < 12){
                        adapter.setState(BaseRecyclerAdapter.STATE_NO_MORE,true);
                    }
                    if(list.size() == 0) pageNum--;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if(pageNum >1){
                    pageNum--;
                }
                onComplate();
            }

            @Override
            public void onFinished() {
                onComplate();
            }
        });
    }

    public void onComplate(){
        mRecyclerRefreshLayout.onComplete();
        isRefreshing = false;
    }

    @Override
    public void onItemButtonClick(int position, int flag) {
        final String serviceid = adapter.getItems().get(position).getServiceid();
        String ordercode = adapter.getItems().get(position).getOrdercode();
        String price = adapter.getItems().get(position).getMoney_total();
        switch (flag){
            case 0: //取消
                NiceDialog.init()
                        .setLayoutId(R.layout.confirm_dialog_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                holder.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                                holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                        cancelOrFinish(serviceid,"1");
                                    }
                                });
                            }
                        })
                        .setMargin(16)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
            case 1: //支付
                paymentDialog(ordercode,price);
                break;
            case 2: //追加金额
                NiceDialog.init()
                        .setLayoutId(R.layout.zhuijia_dialog_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                final EditText et_money = holder.getView(R.id.et_money);
                                holder.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });

                                holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        final String moeny = et_money.getText().toString();
                                        if(TextUtils.isEmpty(moeny)){
                                            ToastUtil.show(OrderSearchActivity.this,"追加的金额不能为空");
                                            return;
                                        }
                                        zhujia(serviceid,moeny);
                                        dialog.dismiss();
                                    }
                                });
                            }
                        })
                        .setMargin(16)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
            case 3: //订单完成
                cancelOrFinish(serviceid,"2");
                break;
            case 4: //订单评分
                NiceDialog.init()
                        .setLayoutId(R.layout.comment_dialog_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(final ViewHolder holder, final BaseNiceDialog dialog) {
                                holder.setOnClickListener(R.id.tv_submit, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        XLHRatingBar bar = holder.getView(R.id.ratingBar);
                                        EditText remark = holder.getView(R.id.et_remark);
                                        String score = bar.getCountSelected()+"";
                                        String comment = remark.getText().toString();
                                        LogUtil.Loge("TAG",comment+"::"+score);
                                        if(TextUtils.isEmpty(comment)){
                                            ToastUtil.show(OrderSearchActivity.this,"评论不能为空");
                                            return;
                                        }
                                        comment(serviceid,comment,score);
                                        dialog.dismiss();
                                    }
                                });

                                holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });

                            }
                        })
                        .setMargin(30)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
        }
    }

    @Override
    public void onRefreshing() {
        isRefreshing = true;
        pageNum = 1;
        requestData();
    }

    @Override
    public void onLoadMore() {
        isRefreshing = false;
        pageNum++;
        adapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE,true);
        requestData();
    }

    @Override
    public void onItemClick(int position, long itemId) {
        String serviceid = adapter.getItems().get(position).getServiceid();
        Intent intent = new Intent(this, PublishDetailActivity.class);
        intent.putExtra("serviceid",serviceid);
        startActivity(intent);
    }


    public void cancelOrFinish(String serviceid, String opt){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.service_opt_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("opt",opt);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                ToastUtil.show(OrderSearchActivity.this,msg);
                onRefreshing();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void zhujia(String serviceid, final String money){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.service_addmoney_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("moneypay_online",money);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    if(object.optInt("status") == 1){
                        ToastUtil.show(OrderSearchActivity.this,object.optString("message"));
                        paymentDialog(object.optString("ordercode"),money);
                    }else {
                        ToastUtil.show(OrderSearchActivity.this,object.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void comment(String serviceid,String remark,String score){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.order_comments_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("remark",remark);
        map.put("score",score);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                ToastUtil.show(OrderSearchActivity.this,msg);
                onRefreshing();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    @OnClick({R.id.ll_back,R.id.tv_search})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_search:
                keywords = et_search.getText().toString().trim();
                if(TextUtils.isEmpty(keywords)){
                    keywords = "";
                }
                isRefreshing = true;
                requestData();
                break;
        }
    }
    public void paymentDialog(final String ordercode, final String price){
        NiceDialog.init()
                .setLayoutId(R.layout.zhifu_dialog_layout)     //设置dialog布局文件
                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        TextView textView = holder.getView(R.id.tv_title);
                        textView.setText("支付金额"+price);
                        final TextView tv_weixin = holder.getView(R.id.tv_weixin);
                        final TextView tv_zhifubao = holder.getView(R.id.tv_zhifubao);
                        final TextView tv_jifen = holder.getView(R.id.tv_jifen);
                        holder.setOnClickListener(R.id.iv_close, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.ll_weixin, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#67b8f2"));
                                tv_zhifubao.setTextColor(Color.parseColor("#333333"));
                                tv_jifen.setTextColor(Color.parseColor("#333333"));
                                paytype = "微信支付";
                            }
                        });

                        holder.setOnClickListener(R.id.ll_zhifubao, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#333333"));
                                tv_zhifubao.setTextColor(Color.parseColor("#67b8f2"));
                                tv_jifen.setTextColor(Color.parseColor("#333333"));
                                paytype = "支付宝支付";
                            }
                        });
                        holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                getOrderCode(ordercode,paytype);
                            }
                        });
                        holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                    }
                })
                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                .setShowBottom(true)     //是否在底部显示dialog，默认flase
                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                .show(getSupportFragmentManager());     //显示dialog
    }
    public void getOrderCode(String ordercode, final String paytype){
        SimpleHUD.showLoadingMessage(this,"",AppConfig.isCanCancel);
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.order_pay_set);
        map.put("ordercode",ordercode);
        map.put("paytype",paytype);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if(paytype.equals("微信支付")) {
                        String optString = jsonObject.optString("prepayinfo");
                        JSONObject payObj = new JSONObject(optString);
                        doWeiXinPay(payObj.optString("appid"), payObj.optString("partnerid"), payObj.optString("prepayid"), payObj.optString("noncestr"),
                                payObj.optString("timestamp"), payObj.optString("package"), payObj.optString("sign"));
                    }else {
                        JSONObject payObj = jsonObject.optJSONObject("prepayinfo");
                        doAlipay("车捷派服务","车捷派服务",payObj.optString("OrderCode"),
                                payObj.optString("url_notify"),payObj.optString("partner"),
                                payObj.optString("seller"),payObj.optString("private_key"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onFinished() {
                SimpleHUD.dismiss();
            }
        });
    }
    public void doWeiXinPay(String appId, String partnerId, String prepayId, String nonceStr,
                            String timeStamp,String packageValue, String sign) {
        SimpleHUD.dismiss();
        api = WXAPIFactory.createWXAPI(this,null);
        api.registerApp(appId);
        PayReq req = new PayReq();
        req.appId			= appId;
        req.partnerId		= partnerId;
        req.prepayId		= prepayId;
        req.nonceStr		= nonceStr;
        req.timeStamp		= timeStamp;
        req.packageValue	= packageValue;
        req.sign			= sign;
        api.sendReq(req);
    }
    public void doAlipay(String subject,String body,String out_trade_no,String notify_url,String partner
            ,String seller,String private_key) {
        // 订单
        String orderInfo = PayUitl.getOrderInfo(subject,body,out_trade_no, notify_url, "0.01",partner,seller);
        // 对订单做RSA 签名
        String sign = PayUitl.sign(orderInfo,private_key);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + PayUitl.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                SimpleHUD.dismiss();
                PayTask alipay = new PayTask(OrderSearchActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo,true);
                PayResult payResult = new PayResult(result);
                final String resultStatus = payResult.getResultStatus();
                mRoot.post(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ToastUtil.show(OrderSearchActivity.this, "支付成功");
                            Intent intent = new Intent("com.qu.waibao.PAYMENTSUCCESS");
                            sendBroadcast(intent);
                        }else if (TextUtils.equals(resultStatus, "8000")) {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            ToastUtil.show(OrderSearchActivity.this, "支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtil.show(OrderSearchActivity.this, "支付失败");
                        }
                    }
                });
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver != null){
            unregisterReceiver(receiver);
            receiver = null;
        }
    }
}
